package com.ctn.information.content;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.ctn.information.R;

public class DetailsFragment extends Fragment implements OnKeyListener{
	
	private TextView detail_title;
	private TextView detail_from;
	private WebView detail_content;
	private static int webviewContentWidth = 0; 
	private static int deviceWidth = 0; 
	public DetailsFragment() {
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//===2013-5-27===edit  ===start
		/*
		 * 新建 DetailsFragment类和相应的 layout文件
		 */
		View v=inflater.inflate(R.layout.details_layout,null);
		detail_title=(TextView)v.findViewById(R.id.detail_title);
		detail_from=(TextView)v.findViewById(R.id.detail_from);
		detail_content=(WebView)v.findViewById(R.id.detail_content);
		return v;
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		/*
		 * 初始化数据并模拟耗时操作
		 * 如网络操作
		 */
		//从网络获取数据
		SharedPreferences prefer=getActivity().getSharedPreferences("CurrentSelectedNewId", Context.MODE_PRIVATE);
		String detailId=prefer.getString("SecondMenuId","");
		//获取点击条目的 id 发送至服务器拿到网页内容数据得到jsonStr
//		String jsonStr="{id:'1', title :'aaa', addtime:'2013-05-20 11:11:11', content:'内容数据并带有图片标签信息，注意图片大小位置'}";
		String jsonStr="{id:'1', title :'aaa', addtime:'2013-05-20 11:11:11', content:'<img width=\"656\" height=\"410\" title=\"点击查看源网页\" style=\"width: 302px; height: 189px; top: 0px; left: 345px;\" src=\"http://www.cxyclub.cn/Upload/Images/2012042312/CC1655F762307FF1.gif\" complete=\"complete\" zoom=\"function a(e,I){if(!this.srcWidth||!this.srcHeight){return}if((this.srcWidth>e)||(this.srcHeight>I)){var G=e/this.srcWidth;var H=I/this.srcHeight;if(G<H){this.style.width=e+\"px\";this.style.height=this.srcHeight*G+\"px\";this.zoomRate=G}else{this.style.width=this.srcWidth*H+\"px\";this.style.height=I+\"px\";this.zoomRate=H}}else{this.zoomRate=1;this.style.width=this.srcWidth+\"px\";this.style.height=this.srcHeight+\"px\"}}\" srcWidth=\"656\" srcHeight=\"410\" zoomRate=\"0.460975609756098\" middleY=\"0px\" middleX=\"345.5px\" firstRate=\"0.460975609756098\" firstWidth=\"302px\" firstHeight=\"189px\" __scrollBinded=\"true\"/>'}";
		String url="http://dzm.pfjhome.net/content5/post/100.aspx";
		StringBuffer str=new StringBuffer();
		try {
			InputStream stream =getActivity().getAssets().open("NewsDetail.html");
			BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
			String temp=reader.readLine();
			while (null!=temp) {
				str.append(temp);		
				temp=reader.readLine();
			}
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		WindowManager wm = (WindowManager) getActivity() 
                .getSystemService(Context.WINDOW_SERVICE); 

		deviceWidth = wm.getDefaultDisplay().getWidth(); 
		try {
			JSONObject obj=new JSONObject(jsonStr);
			detail_content.getSettings().setJavaScriptEnabled(true);  
			//loadUrl(url)为测试内容实际内容使用  loadDataWithBaseURL 方式
			try {
				detail_content.getSettings().setDefaultTextEncodingName("utf-8");// 避免中文乱码
				detail_content.addJavascriptInterface(this, "javatojs");
				detail_content.setSelected(true);
				detail_content.setScrollBarStyle(0);
				WebSettings webSetting = detail_content.getSettings();
				webSetting.setJavaScriptEnabled(true);
				webSetting.setPluginsEnabled(true);
				webSetting.setNeedInitialFocus(false);
				webSetting.setSupportZoom(true);

				webSetting.setDefaultFontSize(20);
				webSetting.setCacheMode(WebSettings.LOAD_DEFAULT
						| WebSettings.LOAD_CACHE_ELSE_NETWORK);
				// 双击全屏
//				detail_content.setOnTouchListener(new OnTouchListener() {
//					@Override
//					public boolean onTouch(View v, MotionEvent event) {
//						return gestureScanner.onTouchEvent(event);
//					}
//				});
				detail_content.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
				detail_content.setWebViewClient(new WebViewClient() {
			     @Override
                public void onPageFinished(WebView view, String url) {
//			    	 detail_content.loadUrl("javascript:window.HTMLOUT.getContentWidth(document.getElementsByTagName('html')[0].scrollWidth);");
			    	 detail_content.loadUrl("javascript:window.HTMLOUT.setContentWidth("+deviceWidth+");");
               } 
          }); 
			} catch (Exception ex) {
				Toast.makeText(getActivity(), "错误",
						Toast.LENGTH_SHORT).show();
			}
//			detail_content.loadUrl(url);
			String detail="";
			if(str!=null){
				detail=str.toString();
			}
			String imagStr=obj.getString("content");
			if(imagStr.indexOf("<img")!=-1){
				
				String beforeStr=imagStr.substring(0,imagStr.indexOf("<img"));
				String temp=imagStr.substring(imagStr.indexOf("<img"));
				String middleStr=temp.substring(0,temp.indexOf("/>"));
				String afterStr=temp.substring(temp.indexOf("/>"));
				if(middleStr.indexOf("style=\"")!=-1||middleStr.indexOf("style=\'")!=-1){
					if(middleStr.indexOf("style=\"")!=-1){
						String beforeStyleStr=middleStr.substring(0,imagStr.indexOf("style=\"")+7);
						String styleTemp=middleStr.substring(imagStr.indexOf("style=\"")+7);
						String styleStr="width: "+deviceWidth/2+"px; height: 100px;\"";
						String styleAfterStr=styleTemp.substring(styleTemp.indexOf("\"")+1);
						middleStr =beforeStyleStr +  styleStr + styleAfterStr;
					}
					if(middleStr.indexOf("style=\'")!=-1){
						String beforeStyleStr=middleStr.substring(0,imagStr.indexOf("style=\'")+7);
						String styleTemp=middleStr.substring(imagStr.indexOf("style=\'")+7);
						String styleStr="width: "+deviceWidth/2+"px; height: 100px;\'";
						String styleAfterStr=styleTemp.substring(styleTemp.indexOf("\'")+1);
						middleStr =beforeStyleStr +  styleStr + styleAfterStr;
					}
				}
				imagStr =beforeStr + middleStr +afterStr;
			}
			detail=detail.replace("null", "");
			detail=detail.replace("#detail_title#", obj.getString("title"));
			detail=detail.replace("#detail_add_time#", obj.getString("addtime"));
			detail=detail.replace("#content#",imagStr);
			detail_content.loadDataWithBaseURL(null,detail, "text/html",  "utf8",null);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

		
	}
	
	class JavaScriptInterface { 
		public void getContentWidth(String value) { 
               if (value != null) { 
                   webviewContentWidth = Integer.parseInt(value); 
                   Log.d("TAG", "Result from javascript: " + webviewContentWidth); 
                   Toast.makeText(getActivity(), 
                           "ContentWidth of webpage is: " + 
  webviewContentWidth                                 + 
  "px", Toast.LENGTH_SHORT).show(); 
              } 
          } 
       } 

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}
}
